#include<t_stdio.h>
#include<t_file.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include<unistd.h>
#include<time.h>
#include<pthread.h>
#include <string.h>

#define bufferlen 1024 //发送/接收数据缓冲区大小
#define server_port 8888 //端口
#define backlog 5 //监听队列
#define max_pthread 3 //最大线程数

//线程处理业务函数
pthread_mutex_t ALOCK = PTHREAD_MUTEX_INITIALIZER ;//创建互斥量

static void * handle_request(void * argv){
    int s_s = *((int *) argv);
    int s_c;
    struct sockaddr_in from ;
    socklen_t len = sizeof(from);
    for(;;){
        time_t now;
        char buf [bufferlen];
        int n=0;

        pthread_mutex_lock(&ALOCK); //进入互斥区
        s_c = accept(s_s , (struct sockaddr *)&from , &len);//接收请求
        pthread_mutex_unlock(&ALOCK); //离开互斥区
        memset(buf , 0 ,bufferlen);
        n = recv(s_c , buf , bufferlen , 0);//接收数据
        
        if(n > 0 && !strncmp(buf , "TIME" , 4))//判断是否为合法接收数据
        {
            memset(buf ,0 ,bufferlen);
            now = time(NULL);
            sprintf(buf , "%24s\r\n",ctime(&now));//时间写入buf
            send(s_c , buf , strlen(buf) , 0);//发送给客户端

        }
        close(s_c);
    }
    return ;

}

//线程创建函数
static void handle_connect(int s){
    int s_s =s;
    pthread_t thread_do[max_pthread];//创建线程数组
    int i=0;
    //创建线程，每一次创建调用线程处理函数
    for(i = 0; i<max_pthread;i++){
        pthread_create(&thread_do[i] , NULL, handle_request , (void *)&s_s);
    }
    //等待线程结束
    for(i = 0; i<max_pthread;i++){
        pthread_join(thread_do[i] , NULL);

    }

}

int main(int argc ,char * argvp[]){
    int s_s;
    struct sockaddr_in local ;//本地地址
    s_s = socket(AF_INET , SOCK_STREAM , 0);
    memset(&local , 0 , sizeof(local));
    local.sin_family = AF_INET;
    local.sin_addr.s_addr = htonl(INADDR_ANY);
    local.sin_port = htons(server_port);

    bind(s_s , (struct sockaddr *)&local ,sizeof(local));//连接本地地址
    listen(s_s , backlog);//创建监听队列
    handle_connect(s_s);
    close(s_s);

    return 0;
}